import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  // baseURL: 'http://ihrm-java.itheima.net/api', // url = base url + request url
  baseURL: process.env.VUE_APP_BASE_API,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(

  config => {
    // do something before request is sent
    const token = store.state.user.token
    if (token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
service.interceptors.response.use(response => {
  // 从axios的data中解构出来必要的字段
  const data = response.data
  // 如果success为true,直接返回data即可
  if (data.success) {
    // console.log(data.success)
    // console.log(data)
    return data
  } else {
    // 如果success为false 业务出错,直接触发reject 被catch分支捕获
    console.log('错误', data.message)

    return Promise.reject(new Error(data.message))
  }
}, error => {
  if (error.response && error.response.data && error.response.data.code === 10002) {
    console.log('搓搓')
    Message({
      message: '失效请重新登录',
      type: 'error',
      duration: 5 * 1000
    })
    // token失效了
    // 1. 手动执行logout, 删除token
    store.dispatch('user/logout')
    // 2. 回到登陆页
    router.push('/login')
  } else {
    Message({
      message: '错了 ',
      type: 'error',
      duration: 5 * 1000
    })
  }
  // if (error.response && error.response.data && error.response.data.code === 10003) {
  //   console.log('我在10003对了')
  // } else {
  //   console.log('我在10003错了')
  // }
  return Promise.reject(error) // 返回执行错误 让当前的执行链跳出成功 直接进入 catch
})

// response interceptor
// service.interceptors.response.use(
//   /**
//    * If you want to get http information such as headers or status
//    * Please return  response => response
//   */

//   /**
//    * Determine the request status by custom code
//    * Here is just an example
//    * You can also judge the status by HTTP Status Code
//    */
//   response => {
//     // const res = response.data
//     const data = response.data
//     console.log('拦截器中response是', response, data)
//     // 后端接口有约定：如果成功，则success是true
//     if (data.success) {
//       return data
//     } else {
//       // 如果操作不成功，直接返回错误
//       return Promise.reject(new Error(data.message))
//     }
//     // if the custom code is not 20000, it is judged as an error.
//   },
//   error => {
//     if (error.response && error.response.data && error.response.data.code === 10002) {
//       Message({
//         message: '请重新登陆',
//         type: 'error',
//         duration: 5 * 1000
//       })
//       console.log(1)
//       store.dispatch('user/logout')
//       console.log(2)
//       router.push('/login')
//       console.log(3)
//     }
//     console.log('haha')
//     console.log('err' + error) // for debug

//     Message({

//       message: '用户登录失效请重新登陆',
//       type: 'error',
//       duration: 5 * 1000
//     })
//     return Promise.reject(error)
//   }
// )

export default service
